package com.leetcode.p400;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

public class Test451 {

    public String frequencySort(String s) {
        HashMap<Character, Integer> hashMap = new HashMap<>();

        List<Map.Entry<Character, Integer>> list = new ArrayList<>();

        for (int i = 0; i < s.length(); i++) {
            Character cChar = s.charAt(i);
            if (hashMap.containsKey(cChar)) {
                hashMap.put(cChar, hashMap.get(cChar) + 1);
            } else {
                hashMap.put(cChar, 1);
            }
        }

        list.addAll(hashMap.entrySet());
        ValueComparator vc = new ValueComparator();
        Collections.sort(list, vc);

        StringBuilder result = new StringBuilder();

        list.forEach(new Consumer<Map.Entry<Character, Integer>>() {
            @Override
            public void accept(Map.Entry<Character, Integer> characterIntegerEntry) {
                for (int i = 0; i < characterIntegerEntry.getValue(); i++) {
                    result.append(characterIntegerEntry.getKey());
                }
            }
        });

        return result.toString();
    }

    private class ValueComparator implements Comparator<Map.Entry<Character, Integer>> {
        public int compare(Map.Entry<Character, Integer> mp1, Map.Entry<Character, Integer> mp2) {
            return mp2.getValue() - mp1.getValue();
        }
    }

    public static void main(String[] args) {
        Test451 test = new Test451();
        System.out.println(test.frequencySort("traeeaadeffaaddcee"));
    }

}
